import javax.sound.sampled.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MusicPlayer implements Runnable {
    File soundFile;
    Thread thread;
    boolean circulate;
    static Clip music = null;

    public MusicPlayer(String filepath, boolean circulate) throws FileNotFoundException {
        this.circulate = circulate;
        this.soundFile = new File(filepath);
        if (!this.soundFile.exists()) {
            throw new FileNotFoundException(filepath);
        }
    }


    public void run() {
        try {
            music = AudioSystem.getClip(); // 获取可用于播放音频文件或音频流的数据流
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);//获得指示格式的音频输入流
            music.open(ais);
            music.start();    //开始播放音乐
            if (circulate) {
                music.loop(Clip.LOOP_CONTINUOUSLY); // 设置音乐循环播放
            }
        } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        this.thread = new Thread(this);
        this.thread.start();
    }

}